package com.jiedeng.util;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

public class QiniuUtil {
    private static Logger logger = LoggerFactory.getLogger(QiniuUtil.class);

    //设置好账号的ACCESS_KEY和SECRET_KEY
    public static String ACCESS_KEY = "8mAy18ftJZ0Napa1N2WJJ4y4n6dZcqpLR7dEIEca"; //这两个登录七牛 账号里面可以找到
    public static String SECRET_KEY = "T20ujfKxVjVgyGSrME10DD1ROzejAiFQ3tkHKfu0";

    //要上传的空间
    String bucketname = "elecinspection"; //对应要上传到七牛上 你的那个路径（自己建文件夹 注意设置公开）

    //密钥配置
    Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    //创建上传对象
    UploadManager uploadManager = new UploadManager();

    //简单上传，使用默认策略，只需要设置上传的空间名就可以了
    public String getUpToken(){
        return auth.uploadToken(bucketname);
    }

    //普通上传
    public Response upload(String filePath, String key) throws IOException{
        try {
            //调用put方法上传
            Response res = uploadManager.put(filePath, key, getUpToken());
            //打印返回的信息
            System.out.println(res.bodyString());
            return res;
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                //响应的文本信息
                System.out.println(r.bodyString());
                logger.error("七牛异常2:" + e.getMessage());
            } catch (QiniuException e1) {
                //ignore
            }
            return r;
        }
    }
    /**
     * 上传文件到七牛
     *
     * @param file
     * @param key
     * @return
     * @throws IOException
     */

    public Response uploadFile(MultipartFile file, String key) throws IOException {
        try {
            //调用put方法上传
            Response res = uploadManager.put(file.getBytes(), key, getUpToken());
            //打印返回的信息
            if (res.isOK() && res.isJson()) {
                //打印返回的信息
                System.out.println(res.bodyString());
                return res;
            } else {
                logger.error("七牛异常1:" + res.bodyString());
                return null;
            }
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            System.out.println(r.toString());
            try {
                //响应的文本信息
                System.out.println(r.bodyString());
                logger.error("七牛异常2:" + e.getMessage());
            } catch (QiniuException e1) {
                //ignore
            }
            return r;
        }
    }
}